package com.icloud.common.web.util;

import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.symmetric.AES;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class AesUtil {
    private static String aesKey;
    @Value("${icloud.aes.key:ajiOXWImKjClP4fe}")
    private String aesKeyValue;

    @PostConstruct
    public void init() {
        aesKey = aesKeyValue;
    }

    /**
     * 加密初始化（AES CBC 填充pkcs7padding，数据块128位）
     */
    private static AES getAes() {
        return new AES("CBC", "PKCS7Padding",
                // 密钥，可以自定义
                aesKey.getBytes(),
                // iv加盐，按照实际需求添加
                "F6pquPegrrP4Tcf1".getBytes());
    }

    /**
     * 核心数据加密（如手机号、身份证号）
     *
     * @param content 加密内容
     */
    public static String encryptData(String content) {
        AES aes = getAes();
        return aes.encryptHex(content);
    }

    /**
     * 核心数据解密（如手机号、身份证号）
     *
     * @param encryptHex 解密内容
     */
    public static String decryptData(String encryptHex) {
        if (encryptHex == null || encryptHex.length() == 0) {
            return "";
        }
        AES aes = getAes();
        try {
            return aes.decryptStr(encryptHex);
        } catch (CryptoException cryptoException) {
            return "";
        }
    }
}
